package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.bo.ContactRelationBo;
import com.pactera.madp.cp.api.dto.contact.ContactUniqueQrCodeQueryDto;
import com.pactera.madp.cp.api.entity.ContactRelation;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.vo.contact.ContactRelationVo;
import com.pactera.madp.cp.mapper.ContactRelationMapper;
import com.pactera.madp.cp.service.ContactRelationService;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class ContactRelationServiceImpl extends ServiceImpl<ContactRelationMapper, ContactRelation> implements ContactRelationService{

    private IWorkContactService contactService;
    private IWorkEmployeeService employeeService;
    private ContactRelationMapper contactRelationMapper;

    @Override
    public R<IPage<ContactRelationVo>> getJoinContacts(Page<ContactRelationBo> page, ContactUniqueQrCodeQueryDto dto) {
        Page<ContactRelationVo> resultPage = new Page<>();

        //获取邀请客户主键id
        WorkContactEntity contactEntity = contactService.getWorkContactByWxExternalUserId(dto.getWxExternalUserid());
        if(contactEntity == null) {
            return R.ok(resultPage);
        }
        Integer contactId = contactEntity.getId();

        //获取企业成员主键id
        WorkEmployeeEntity employeeEntity = employeeService.getWorkEmployeeByWxUserId(dto.getWxUserId(), "id");
        if(employeeEntity == null) {
            return R.ok(resultPage);
        }
        Integer employeeId = employeeEntity.getId();

        //获取邀请客户列表
        List<ContactRelationVo> voList = contactRelationMapper.getJoinContacts(page, contactId, employeeId).stream().map(crb -> {
            ContactRelationVo vo = new ContactRelationVo();
            vo.setName(crb.getName());
            vo.setAvatar(crb.getAvatar());
            vo.setTypeDesc(crb.getType() == 2 ? crb.getCorpName() : "微信");
            vo.setJoinTime(crb.getCreateTime());
            return vo;
        }).collect(Collectors.toList());

        BeanUtil.copyProperties(page, resultPage,new String[]{"records","optimizeCountSql"});
        resultPage.setRecords(voList);
        return R.ok(resultPage);
    }


}
